<template>
  <div>
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px">
      <el-form-item label="员工姓名：" prop="name">
        <el-input v-model="ruleForm.realname" />
      </el-form-item>
      <el-form-item label="手机号：" prop="mobile">
        <el-input v-model="ruleForm.mobile" />
      </el-form-item>
      <el-form-item label="职位：">
        <el-input v-model="ruleForm.position" />
      </el-form-item>
      <el-form-item label="账号：" prop="tenant_name">
        <el-input v-model="ruleForm.tenant_name" />
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input v-model="ruleForm.password" show-passwor placeholder="请输入密码" />
      </el-form-item>
      <el-form-item label="编辑权限" prop="auth_rule_sell" class="authority">
        <el-tree
          ref="tree"
          :data="routes"
          show-checkbox
          node-key="id"
          :default-expanded-keys="keys"
          :default-checked-keys="[1, 2]"
        />
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { addAdministrator, editAdministrator } from '@/api/authority'
import asyncRoutes from '@/router/b'
const ERR_OK = 200
const phoneValidate = (rule, value, callback) => {
  const isRight = /^1[3456789]\d{9}$/.test(value)
  if (!isRight) {
    return callback(new Error('请输入有效手机号码'))
  } else {
    callback()
  }
}
export default {
  props: {
    id: {
      type: [String, Number],
      default: ''
    },
    authInfo: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      ruleForm: {
        realname: '',
        mobile: '',
        position: '',
        tenant_name: '',
        password: '',
        auth_rule_sell: []
      },
      rules: {
        realname: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        mobile: [
          { trigger: 'blur', validator: phoneValidate }
        ],
        position: [{ required: true, message: '请输入职位', trigger: 'blur' }],
        tenant_name: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        auth_rule_sell: [
          { required: true, message: '请选择权限', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    routes() {
      const arr = []
      for (let i = 0; i < asyncRoutes.length; i++) {
        const obj = asyncRoutes[i]
        if (obj.meta) {
          obj.label = obj.meta.title
          obj.id = obj.meta.id
        }
        // if (obj.id === 1) {
        //   obj.disabled = true
        // }
        if (obj.children && obj.id) {
          const obj_b = obj.children
          for (let j = 0; j < obj_b.length; j++) {
            obj_b[j].label = obj_b[j].meta.title
            obj_b[j].id = obj_b[j].meta.id
            // if (obj_b[j].id === 2) {
            //   obj_b[j].disabled = true
            // }
          }
          obj.children = obj_b
        }
        arr.push(obj)
      }
      return arr
    },
    keys() {
      const arr = []
      for (let i = 0; i < asyncRoutes.length; i++) {
        const obj = asyncRoutes[i]
        if (obj.children) {
          for (let j = 0; j < obj.children.length; j++) {
            const obj_b = obj.children[j]
            arr.push(obj_b.id)
          }
        }
      }
      return arr
    }
  },
  watch: {
    authInfo(newVal) {
      this.ruleForm.name = newVal.realname
      this.ruleForm.mobile = newVal.mobile
      this.ruleForm.position = newVal.position
      this.ruleForm.tenant_name = newVal.tenant_name
      if (newVal.auth_rule_sell) {
        this.$refs.tree.setCheckedKeys(JSON.parse(newVal.auth_rule_sell))
        this.ruleForm.auth_rule_sell = JSON.parse(newVal.auth_rule_sell)
      } else {
        this.$refs.tree.setCheckedKeys(this.getAllCheckKeys())
        this.ruleForm.auth_rule_sell = this.getAllCheckKeys()
      }
    }
  },
  methods: {
    addAdmini() {
      // this._addAdministrator(this.ruleForm)
      const adminArr = this.$refs.tree.getCheckedKeys()
      console.log(adminArr, '添加权限数组')
      this.ruleForm.auth_rule_sell = adminArr.concat(this.$refs.tree.getHalfCheckedKeys())
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this._addAdministrator(this.ruleForm)
            .then(() => {
              this.$emit('added')
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    editAdmini() {
      this.ruleForm.id = this.id
      const adminArr = this.$refs.tree.getCheckedKeys()
      this.ruleForm.auth_rule_sell = adminArr
      this._editAdministrator(this.ruleForm)
        .then((res) => {
          this.$emit('upDated')
        })
        .catch(err => {
          console.log(err)
        })
    },
    getAllCheckKeys() {
      const arr = []
      for (let i = 0; i < asyncRoutes.length; i++) {
        const item = asyncRoutes[i]
        arr.push(item.id)
        if (item.children) {
          const obj_child = item.children
          for (let j = 0; j < obj_child.length; j++) {
            arr.push(obj_child[j].id)
          }
        }
      }
      return arr
    },
    _addAdministrator({ tenant_name, password, auth_rule_sell, mobile, position, realname }) {
      return new Promise((resolve, reject) => {
        addAdministrator({ tenant_name, password, auth_rule_sell, mobile, position, realname })
          .then(res => {
            if (res.code === ERR_OK) {
              console.log(res)
              this.$message({
                showClose: true,
                message: res.message,
                type: 'success'
              })
              resolve()
            }
          })
          .catch(err => {
            console.log(err)
            reject()
          })
      })
    },
    _editAdministrator({ password, auth_rule_sell, mobile, position, realname, id }) {
      return new Promise((resolve, reject) => {
        editAdministrator({ password, auth_rule_sell, mobile, position, realname, id })
          .then(res => {
            if (res.code === ERR_OK) {
              console.log(res)
              this.$message({
                showClose: true,
                message: res.message,
                type: 'success'
              })
            }
            resolve(res)
          })
          .catch(err => {
            console.log(err)
            reject(err)
          })
      })
    }

  }
}
</script>
<style lang="scss" scoped>
.el-input /deep/ .el-input__inner {
  width: 414px !important;
}
.el-tree {
  display: flex;
  justify-content: flex-start;
  margin-top: 40px;
  .el-tree-node {
    margin-right: 15px;
  }
}
.authority /deep/ .el-form-item__content {
  margin-left: 25px !important;
}
</style>
